/**
 * Created by bai on 2017/7/18.
 */
var layer;
var form;
layui.use(['layer', 'form', 'element', 'laydate'], function () {
    layer = layui.layer;
    form = layui.form();
    var element = layui.element;
    var laydate = layui.laydate;
    var start = {
        min: '1970-01-01 00:00:00',
        max: '2099-06-16 23:59:59',
        istoday: false,
        choose: function (datas) {
            end.min = datas; //开始日选好后，重置结束日的最小日期
            end.start = datas //将结束日的初始值设定为开始日
        }
    };

    var end = {
        min: '1970-01-01 00:00:00',
        max: '2099-06-16 23:59:59',
        istoday: false,
        choose: function (datas) {
            start.max = datas; //结束日选好后，重置开始日的最大日期
        }
    };

    document.getElementById('startDate').onclick = function () {
        start.elem = this;
        laydate(start);
    }
    document.getElementById('endDate').onclick = function () {
        end.elem = this
        laydate(end);
    }
    //layer.msg('Hello World');


    form.on('checkbox', function (val) {
            var d = JSON.parse($(this).parent().parent().attr("data-str"))
            console.info(val.elem.checked);
            var layer = typhoonMap.t_layers[d.id].t_layer_group.getLayers()[0];
            if (!val.elem.checked) {
                layer.setStyle({fillOpacity: 0, color: "#8784F5", weight: 2})
            } else {
                layer.setStyle({fillOpacity: 0.3, color: "#00FFFF", weight: 3})
            }
        }
    )
});

$(function () {
    var count = 0;
    jQuery('.right-cart').click(function (e) {
        count++;
        if (count % 2 == 0) {
            $(this).closest('.rightMenu').animate({
                left: '-365px'
            });
            $(this).html("<br/>点<br/>击<br/>展<br/>开<br/>");
        } else {
            $(this).closest('.rightMenu').animate({
                left: '0px'
            });

            $(this).html("<br/>点<br/>击<br/>关<br/>闭<br/>");
        }
    })
    $('button.event-ctrl').click(function () {
        var idStr = this.id;
        typhoonMap.map.once('click', function (e) {
            // alert(idStr+":"+e.latlng);
            $('#' + idStr + '-lng').val(e.latlng.lng);
            $('#' + idStr + '-lat').val(e.latlng.lat);
        })
    });
    function parseLatLngs(d) {
        var latlngs = [
            [parseFloat(d.lowerLeftCoordinate.split(",")[0]), parseFloat(d.lowerLeftCoordinate.split(",")[1])],
            [parseFloat(d.upperLeftCoordinate.split(",")[0]), parseFloat(d.upperLeftCoordinate.split(",")[1])],
            [parseFloat(d.upperRightCoordinate.split(",")[0]), parseFloat(d.upperRightCoordinate.split(",")[1])],
            [parseFloat(d.lowerRightCoordinate.split(",")[0]), parseFloat(d.lowerRightCoordinate.split(",")[1])]
        ];
        return latlngs;
    }

    function appendResultTable(container, data) {
        // console.info(container);
        container.append('<tr data-str=\'' + JSON.stringify(data) + '\'>' +
            '<td><input class="shandowed" type="checkbox" lay-skin="primary"></td>' +
            '<td><img src="' + data.browseUrl + '" style="width:80px;height: 80px;"></td>' +
            '<td> <p>数据标识：' + data.displayId + '</p> ' +
            // '<p>条代号：123 行编号：33</p> ' +
            '<p>影像四至边界' + data.sceneBounds + '</p> ' +
            '<p>日期：' + data.acquisitionDate + '</p> </td></tr>');

    }

    function validateDateParam() {
        var startDate = $("#startDate").val();
        var endDate = $("#endDate").val();
        if (startDate == "" || endDate == "") {
            layer.msg("开始时间或者结束时间不能为空");
        } else {
            return true;
        }
        return false;
    }

    function isNumber(value) {
        var patrn = /^(-)?\d+(\.\d+)?$/;
        if (patrn.exec(value) == null || value == "") {
            return false
        } else {
            return true
        }
    }

    function valudateLatLngParam() {
        var minlat = $('#right-down-lat').val();
        var maxlat = $('#left-up-lat').val();
        var minlng = $('#left-up-lng').val();
        var maxlng = $('#right-down-lng').val();

        if (isNumber(minlat) && isNumber(maxlat) && isNumber(minlng) && isNumber(maxlng)) {
            if ((minlat > maxlat) || (minlng > maxlng)) {
                layer.msg("左上角和右下角坐标值不正确");
            } else {
                return true;
            }
        } else {
            layer.msg("坐标值不正确");
        }
        return false;
    }

    $("#result-table").delegate("tr", "click", function () {
//        var layer = typhoonMap.t_layers.getLayers()[0];
        var d = JSON.parse($(this).attr("data-str"))
        if ($(this).hasClass("on")) {
            $(this).removeClass("on");
            clearImg(d.id);
        } else {
            $(this).addClass("on");
            drawImg(d._id, d.browseUrl, d.boundary.coordinates[0]);
        }


    })
    $("#search").click(function () {
        if (!validateDateParam()) {
            return;
        }
        if (!valudateLatLngParam()) {
            return;
        }
        $.ajax({
            url: "search-by-data.ajax",
            data: {
                startDate: $("#startDate").val(),
                endDate: $("#endDate").val(),
                minLat: $('#right-down-lat').val(),
                maxLat: $('#left-up-lat').val(),
                minLng: $('#left-up-lng').val(),
                maxLng: $('#right-down-lng').val()
            },
            success: function (data) {
                console.info(data);
                $('#result-table').empty();
                for (var i = 0, len = data.length; i < len; i++) {
                    var d = data[i];
                    var latlngs = parseLatLngs(d);
                    drawPoly(d.id, latlngs);
                    appendResultTable($('#result-table'), d);
                }
                form.render();
                // typhoonMap.map.fitBounds([[22.05533, 110.92066], [22.15883, 110.92066], [22.15883, 111.14889], [22.05533, 111.14889]]);
            }
        });

        jQuery("#result").show();
    });
});